<template>
  <div class='sub-category'>
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区 -->
      <SubFilter @filterChange="changeFilter" />
      <!-- 结果区域 -->
      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sortChange="changeSort" />
        <!-- 列表 -->
        <ul>
          <li v-for="item in goodsList" :key="item.id" >
            <GoodsItem :goods="item" />
          </li>
        </ul>
        <!-- 无限加载 -->
        <XtxInfiniteLoading  :loading="loading" :finished="finished" @infinite="getData" />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'SubCategory'
}
</script>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { findSubCategoryGoods } from '@/api/category'
import { filterParamsType, sortParamsType } from '@/types/paramsTypes'
import { newGoodType } from '@/types/resultsType'
import SubBread from './components/subBread.vue'
import SubFilter from './components/subFilter.vue'
import SubSort from './components/subSort.vue'
import GoodsItem from './components/goodsItem.vue'

const route = useRoute()

const loading = ref(false)
const finished = ref(false)
// 商品列表
const goodsList = ref<newGoodType[]>([])
// 查询参数
let reqParams = {
  categoryId: '',
  page: 1,
  pageSize: 20
}
// 筛选参数
let filterParams: filterParamsType = {
  brandId: undefined
}
// 排序参数
let sortParams: sortParamsType = {
  inventory: false,
  onlyDiscount: false,
  sortField: undefined,
  sortMethod: undefined
}
// 获取数据
const getData = () => {
  // 开启加载状态
  loading.value = true
  reqParams.categoryId = (route.params.id as string)
  // 获取数据
  findSubCategoryGoods({
    ...reqParams,
    ...filterParams,
    ...sortParams
  }).then(({ result }) => {
    if (result.items.length) {
      // 有数据则追加到列表,页数+1
      goodsList.value.push(...result.items)
      reqParams.page++
    }else {
      // 没有数据则加载完毕
      finished.value = true
    }
    // 请求结束,关闭加载状态
    loading.value = false
  })
}
// 切换二级分类需要重新加载
watch(() => route.params.id, (newVal) => {
  if (newVal && route.path === ('/category/sub/' + newVal)) {
    goodsList.value = []
    reqParams = {
      categoryId: '',
      page: 1,
      pageSize: 20
    }
    finished.value = false
  }
})
// 监听筛选区改变
const changeFilter = (filter: filterParamsType) => {
  filterParams = filter
  reqParams.page = 1
  goodsList.value = []
  finished.value = false
}
// 监听排序改变
const changeSort = (sort: sortParamsType) => {
  sortParams = sort
  reqParams.page = 1
  goodsList.value = []
  finished.value = false
}
</script>
<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>